import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.List;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.UIManager;

public class SystemWindow extends Frame implements ActionListener
{
	JxtaApplication application;
	List listLog;
	Panel topPanel;

	enum Buttons
	{
		publisher, manager, finder
	}

	SystemWindow(String titlu)
	{
		super(titlu);
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (Exception e)
		{
			Log("Could not set look-and-feel");
		}
		setSize(800, 500);

		addContentToTheFrame();

		this.addWindowListener(new WindowAdapter()
		{
			@Override
			public void windowClosing(WindowEvent e)
			{
				if (application != null)
				{
					application.Terminate();
				}
				System.exit(0);
			}
		});
		setVisible(true);
	}

	private void addContentToTheFrame()
	{
		setLayout(new BorderLayout());

		topPanel = new Panel();
		topPanel.setLayout(new FlowLayout());
		topPanel.setSize(getWidth(), 100);

		Button btnStartPublisher = new Button();
		btnStartPublisher.setLabel("Start publisher");
		btnStartPublisher.setActionCommand(Buttons.publisher.toString());
		btnStartPublisher.addActionListener(this);

		Button btnStartManager = new Button();
		btnStartManager.setLabel("Start manager");
		btnStartManager.setActionCommand(Buttons.manager.toString());
		btnStartManager.addActionListener(this);

		Button btnStartFinder = new Button();
		btnStartFinder.setLabel("Start finder");
		btnStartFinder.setActionCommand(Buttons.finder.toString());
		btnStartFinder.addActionListener(this);

		listLog = new List();

		topPanel.add(btnStartPublisher);
		topPanel.add(btnStartManager);
		topPanel.add(btnStartFinder);

		add(topPanel, BorderLayout.NORTH);
		add(listLog, BorderLayout.CENTER);
	}

	public void Log(String message)
	{

		listLog.add(message);
		listLog.select(listLog.getItemCount() - 1);

	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		for (int i = 0; i < topPanel.getComponentCount(); i++)
		{
			topPanel.getComponent(i).setEnabled(false);
		}
		Buttons buttonAction = Buttons.valueOf(e.getActionCommand());
		if (application != null)
		{
			application.Terminate();
		}
		if (buttonAction == Buttons.publisher)
		{
			application = new ServicePublisher();
		}
		else
		{
			if (buttonAction == Buttons.manager)
			{
				application = new ServiceManager();
			}
			else
			{
				if (buttonAction == Buttons.finder)
				{
					application = new ServiceFinder();
				}
			}
		}
		if (application != null)
		{
			application.setInterfaceWindow(this);
			application.Start();
		}

	}
}
